from django.shortcuts import render, HttpResponse
from django.http import JsonResponse

from django.views.generic import View
from audit.models import AuditBash

import json
import datetime


def to_datetime(txt):
    return datetime.datetime.strptime(txt, '%Y-%m-%d %H:%M:%S')

class AuditBashList(View):
    def get(self, req):
        all_audit_bash_cmds = AuditBash.objects.all()
        
        return render(
            req, 'all_audits.html',{
                "all_audit_bash_cmds": all_audit_bash_cmds
            }
            
        )

class AuditBashAdd(View):
    def post(self, req):
        body = req.body
        if isinstance(body, bytes):
            body = body.decode('utf-8')
        audit = json.loads(body)
        aud = AuditBash()
        aud.host_ip = audit.get('host_ip', '')
        aud.run_user = audit.get('run_user', '')
        aud.client = audit.get('client', '')
        aud.tty = audit.get('tty', '')
        aud.run_time = to_datetime(audit.get('run_time', ''))
        aud.history_id = audit.get('history_id', '')
        aud.cmd = audit.get('cmd', '')
        aud.send_time = to_datetime(audit.get('send_time', ''))
        print(aud)
        print(aud.host_ip)
        print(aud.client)
        print(aud.send_time)
        print(aud.tty)
        print(aud.cmd)
        # aud.save()
        
        return JsonResponse({
            'status': 200
        })
        